<?php

namespace App\Models\User;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class LiveScoreWater extends Model
{
    public $table = 'live_score_water';
    public $timestamps = false;
    protected $guarded = [];

    #获取流水记录列表
    public static function getWaterList($start_time,$end_time,$type,$search)
    {
        $data = self::with('user')
                ->when(!empty($start_time) && !empty($end_time), function ($query) use ($start_time, $end_time) {
                    return $query->whereBetween('created_time', [Carbon::parse($start_time)->startOfDay(), Carbon::parse($end_time)->endOfDay()]);
                })
                ->when($type > 0, function ($query) use ($type) {
                    return $query->where('type','=',$type);
                })
                ->when($search > 0, function ($query) use ($search) {
                    return $query->where('user_id','like',"%{$search}%");
                })
                ->select('id','user_id','score','type','created_time')
                ->orderByDesc('created_time')
                ->paginate(15)
                ->toArray();
        if (empty($data)) {
            return [];
        } else {
            return $data;
        }
    }

    #创建积分流水记录
    public static function createWater(int $user_id, int $score, int $type)
    {
        $flag = self::create([
                    'user_id'       => $user_id,
                    'score'         => $score,
                    'type'          => $type,
                    'created_time'  => time(),
                ]);
        return $flag;
    }

    #关联用户表
    public function user()
    {
        return $this->hasOne(LiveUser::class,'id','user_id')->select('id','user_name')->withDefault([
            'user_name' => '',
        ]);
    }
}
